// pages/position/position.js
const app = getApp();
const util = require('../../utils/util.js')
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		address: '',
		latitude: '',
		longitude: '',
		detail: '',
		markers: [],
		_openid: '',
		clock_in: '',
		showCon: false,
		marginTop: 0, // 距离顶部高度
	},
		/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getCityNameOFLocation();
		setTimeout(function () {

			wx.hideNavigationBarLoading() //完成停止加载

			wx.stopPullDownRefresh() //停止下拉刷新

		}, 1000);
	},
	changeModalCancel: function(){
      this.setData({
				showCon: false
			})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.startPullDownRefresh()//下拉刷新
		this.setData({
		  _openid : app.getOpenid()
		})
		var that = this;
		setTimeout(function(){
			that.onList();
		},1000)
	}, 
	getCityNameOFLocation: function () {
		var that = this;
		wx.getLocation({
			type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
			success: function (res) {
				console.log("定位成功");
				var latitude = res.latitude;
				var longitude = res.longitude;
				var locationString = latitude + "," + longitude;
				wx.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1',
					data: {
						"key": "L6PBZ-DDR3W-2WURZ-RRK44-XE7T6-74BDV",
						"location": locationString
					},
					method: 'GET',
					// header: {}, 
					success: function (res) {
						// success
						console.log(res.data);
						var address = res.data.result.address
						var detail =  res.data.result.formatted_addresses.rough
						console.log("请求数据:" + address);
						that.setData({
							markers: [{
								iconPath: "",
								id: 0,
								latitude: latitude,
								longitude: longitude,
								width: 50,
								height: 50
							}],
							address: address, 
							detail:detail,
							latitude: latitude,
							longitude: longitude
						})
					},
					fail: function () {
						// fail
						console.log("请求失败");
					},
					complete: function () {
						// complete
						console.log("请求完成");
					}
				})
			},
			fail: function () {
				// fail
        console.log("定位失败");
        wx.getSetting({
          success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
        that.setData({
          showCon: true
        })
        }
        }
        })
			},
			complete: function () {
				// complete
				console.log("定位完成");
			}
		})
	},
	//添加位置信息
   onAdd: function(){
		 if(this.data.address){
		 var time = util.formatTime(new Date);
      const db = wx.cloud.database();
		 db.collection('position').add({
			 data: {
				 address: this.data.address,
				 detail: this.data.detail,
				 latitude: this.data.latitude,
				 longitude: this.data.longitude,
				 time: new Date(time)
			 },
			 success: res => {
				 // 在返回结果
				 wx.showToast({
					 title: '添加成功',
				 })
				 var that = this;
				 setTimeout(function(){
           that.onList()
				 },1000)
			 },
			 fail: err => {
				 wx.showToast({
					 icon: 'none',
					 title: '添加失败'
				 })
				 console.error('[数据库] [新增记录] 失败：', err)
			 }
			 })
		 }else {
			  wx.showToast({
					title: '请打开位置服务，才可以打卡',
					icon: 'none'
				})
		 }
	 },
	 //查询打卡记录
	 onList: function(){
    const db = wx.cloud.database();
		 db.collection('position').where({
			 _openid: this.data._openid
		 }).skip(0).orderBy('time', 'desc')
			 .get({
				 success: res => {
					 console.log(res.data);
					 if(res.data.length>0){
					 var info = [{}];
					 for (var i = 0; i < res.data.length; i++) {
						 var date = new Date(res.data[i].time);
						 var date_value = util.formatTime(date);
						 info[i] = { time: date_value, address: res.data[i].address, detail:res.data[i].detail };
						 // console.log(date_value)
					 }
					 this.setData({
						 clock_in: info
					 })
					 }
					 // console.log('[数据库] [查询记录] 成功: ', this.data.clock_in)
				 },
				 fail: err => {
					 wx.showToast({
						 icon: 'none',
						 title: '查询失败',
					 })
					 console.log(' 获取 clock_in 失败，请检查是否有部署云函数，错误信息：', err)
				 }
			 });
	 },
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady(e) {
	  var that = this
    // 页面渲染完成
    var query = wx.createSelectorQuery();
		query.select('.map').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
			console.log(res)
      var listHeight = res[0].height; // 获取list高度
      that.setData({
        marginTop: listHeight * 2
      })
    });
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})